package cn.edu.bjtu.toychange.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import cn.edu.bjtu.toychange.entity.Message;

public class MessageDao extends BaseDao {
	private Session session;
	
	public MessageDao() {
		session = getSession();
	}
	
	public void saveMessage(Message message) {
		session.beginTransaction();
		session.save(message);
		session.close();
	}
	
	public void deleteMessage(int messageID) {
		session.beginTransaction();
		session.delete(session.load(Message.class, messageID));
		session.close();
	}
	
	public Message getMessage(int messageID) {
		return (Message) getSession().get(Message.class, messageID);
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Message> getUserMessages(int userID) {
		session.beginTransaction();
		List<Message> messageList = session.createQuery("SELECT * FROM MESSAGE WHERE M_senderID = ? OR M_receiverID = ? ORDER BY M_mesTime")
				.setInteger(0, userID).setInteger(1, userID).list();
		session.close();
		
		return (ArrayList<Message>) messageList;
	}
}